<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>聊天</title>
</head>

<body>
    <h3>WebSocket Go 聊天</h3>
    <div id="output"></div>

    <div id="input">
        <textarea id="msg" cols="50" rows="10"></textarea>
        <button type="submit" id="sned-msg">发送</button>
    </div>
    <script>
        var url = 'ws://10.0.0.84:1234/chat-serve';
        var c = new WebSocket(url);

        var nickname = prompt("请输入你的昵称");

        var outputEl = document.getElementById('output')
        var msgEl = document.getElementById('msg')

        // 发送消息
        var send = function (data) {
            c.send(data)
        }

        // 获取消息
        c.onmessage = function (msg) {
            var _el = document.createElement('p')
            _el.innerText = new Date() + " <== " + msg.data
            outputEl.appendChild(_el)
            console.log(msg)
        }

        // 打开连接
        c.onopen = function () {
            send("欢迎[" + nickname + "]进入聊天室")
        }

        // 关闭连接
        c.onclose = function () {
            console.log('[' + nickname + ']退出了聊天室')
        }

        // 发送聊天信息
        document.getElementById('sned-msg').addEventListener('click', function () {
            send(nickname + "：" + msgEl.value)
        })
    </script>
</body>

</html>